package com.ksvip.next.components.core.bean;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import com.ksvip.next.components.core.exception.BusinessException;

import lombok.extern.slf4j.Slf4j;

/**
 * 事件监听类， 通过反射调用传入event中的方法
 */
@Slf4j
public class EventListener {

    /**
     * @param event
     * @throws BusinessException
     */
    @Subscribe
    @AllowConcurrentEvents
    public void listen(Event event) {
        if (null == event) {
            log.error("EventListener.listen() event is null, do nothing");
            return;
        }
        //目标方法参数列表
        Object[] args = event.getArgs();
        //目标方法参数类型列表
        Class<?>[] parameterTypes = event.getClazzs();

        if (null == parameterTypes && null != args && args.length > 0) {
            parameterTypes = new Class[args.length];
            for (int i = 0; i < args.length; i++) {
                parameterTypes[i] = args[i].getClass();
            }
        }
        //取bean的方法对象
        Method method = null;
        try {
            method = event.getBean().getClass().getDeclaredMethod(event.getMethodName(), parameterTypes);
            method.setAccessible(true);
            method.invoke(event.getBean(), args);
        } catch (NoSuchMethodException e) {
            log.error("NoSuchMethodException={}", e);
        } catch (SecurityException e) {
            log.error("SecurityException={}", e);
        } catch (IllegalAccessException e) {
            log.error("IllegalAccessException={}", e);
        } catch (IllegalArgumentException e) {
            log.error("IllegalArgumentException={}", e);
        } catch (InvocationTargetException e) {
            log.error("InvocationTargetException={}", e);
        }
    }
}
